import { Injectable, CanActivate, ExecutionContext, Logger } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
import { TokenService } from '../../modules/token/token.service';

@Injectable()
export class RolesGuard implements CanActivate {
  private readonly logger = new Logger(RolesGuard.name);

  constructor(
    private reflector: Reflector,
    private tokenService: TokenService
  ) {}

  canActivate(context: ExecutionContext): boolean {
    // 获取路由上设置的所需角色
    const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    // 如果没有设置角色要求，则允许访问
    if (!requiredRoles || requiredRoles.length === 0) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    
    // 从请求头中获取token
    const token = this.tokenService.extractTokenFromHeader(request);
    if (!token) {
      this.logger.warn('No token provided for role-protected route');
      return false;
    }

    // 检查用户是否具有所需角色
    return this.tokenService.checkRoles(token, requiredRoles);
  }
} 